<template>
    <div class="student-manage">
        <div class="fixed-header">
            <div class="header-actions">
                <el-button type="primary" @click="handleAdd">新增学生</el-button>
                <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">批量删除</el-button>
                <el-button type="warning" :disabled="!selectedRows.length" @click="handleBatchEdit">批量编辑</el-button>
                <el-button type="success" @click="handleExport">导出Excel</el-button>
                <el-button type="primary" @click="showImportDialog">批量导入</el-button>
                <el-input v-model="searchQuery" placeholder="请输入学号或姓名搜索" style="width: 200px"
                    @keyup.enter="handleSearch" clearable @clear="handleClear">
                    <template #suffix>
                        <el-icon class="el-input__icon" @click="handleSearch">
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
        </div>

        <div class="table-container">
            <el-table :data="sortedAndFilteredList" border style="width: 100%" @selection-change="handleSelectionChange"
                @sort-change="handleSortChange">
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" width="80" :index="getIndex">
                    <template #header>
                        <div class="column-header">
                            <span>序号</span>
                            <el-icon class="sort-icon"
                                :class="{ 'active': sortOrder !== '', 'desc': sortOrder === 'descending' }"
                                @click="toggleSort">
                                <Sort />
                            </el-icon>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="account" label="学号" width="120">
                    <template #header>
                        <div class="column-header">
                            <span :class="{ 'filtered': filters.account }">
                                学号
                                <el-tag v-if="filters.account" size="small" class="filter-tag">1</el-tag>
                            </span>
                            <el-popover placement="bottom" :width="200" trigger="click">
                                <template #reference>
                                    <el-icon class="filter-icon" :class="{ 'is-filtered': filters.account }">
                                        <Filter />
                                    </el-icon>
                                </template>
                                <div class="filter-content">
                                    <el-input v-model="filters.account" placeholder="搜索学号" clearable />
                                </div>
                            </el-popover>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="100">
                    <template #header>
                        <div class="column-header">
                            <span :class="{ 'filtered': filters.name }">
                                姓名
                                <el-tag v-if="filters.name" size="small" class="filter-tag">1</el-tag>
                            </span>
                            <el-popover placement="bottom" :width="200" trigger="click">
                                <template #reference>
                                    <el-icon class="filter-icon" :class="{ 'is-filtered': filters.name }">
                                        <Filter />
                                    </el-icon>
                                </template>
                                <div class="filter-content">
                                    <el-input v-model="filters.name" placeholder="搜索姓名" clearable />
                                </div>
                            </el-popover>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="college" label="学院" width="180">
                    <template #header>
                        <div class="column-header">
                            <span :class="{ 'filtered': filters.college.length }">
                                学院
                                <el-tag v-if="filters.college.length" size="small" class="filter-tag">
                                    {{ filters.college.length }}
                                </el-tag>
                            </span>
                            <el-popover placement="bottom" :width="200" trigger="click">
                                <template #reference>
                                    <el-icon class="filter-icon" :class="{ 'is-filtered': filters.college.length }">
                                        <Filter />
                                    </el-icon>
                                </template>
                                <div class="filter-content">
                                    <el-checkbox-group v-model="filters.college">
                                        <el-checkbox v-for="item in collegeOptions" :key="item" :label="item">
                                            {{ item }}
                                        </el-checkbox>
                                    </el-checkbox-group>
                                </div>
                            </el-popover>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="major" label="专业" width="180">
                    <template #header>
                        <div class="column-header">
                            <span :class="{ 'filtered': filters.major.length }">
                                专业
                                <el-tag v-if="filters.major.length" size="small" class="filter-tag">
                                    {{ filters.major.length }}
                                </el-tag>
                            </span>
                            <el-popover placement="bottom" :width="200" trigger="click">
                                <template #reference>
                                    <el-icon class="filter-icon" :class="{ 'is-filtered': filters.major.length }">
                                        <Filter />
                                    </el-icon>
                                </template>
                                <div class="filter-content">
                                    <el-checkbox-group v-model="filters.major">
                                        <el-checkbox v-for="item in majorOptions" :key="item" :label="item">
                                            {{ item }}
                                        </el-checkbox>
                                    </el-checkbox-group>
                                </div>
                            </el-popover>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="className" label="班级" width="180">
                    <template #header>
                        <div class="column-header">
                            <span :class="{ 'filtered': filters.className.length }">
                                <span>班级</span>
                                <el-tag v-if="filters.className.length" size="small" class="filter-tag">
                                    {{ filters.className.length }}
                                </el-tag>
                            </span>
                            <el-popover placement="bottom" :width="200" trigger="click">
                                <template #reference>
                                    <el-icon class="filter-icon" :class="{ 'is-filtered': filters.className.length }">
                                        <Filter />
                                    </el-icon>
                                </template>
                                <div class="filter-content">
                                    <el-checkbox-group v-model="filters.className">
                                        <el-checkbox v-for="item in classOptions" :key="item" :label="item">
                                            {{ item }}
                                        </el-checkbox>
                                    </el-checkbox-group>
                                </div>
                            </el-popover>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="gender" label="性别" width="100">
                    <template #header>
                        <div class="column-header">
                            <span :class="{ 'filtered': filters.gender.length }">
                                性别
                                <el-tag v-if="filters.gender.length" size="small" class="filter-tag">
                                    {{ filters.gender.length }}
                                </el-tag>
                            </span>
                            <el-popover placement="bottom" :width="200" trigger="click">
                                <template #reference>
                                    <el-icon class="filter-icon" :class="{ 'is-filtered': filters.gender.length }">
                                        <Filter />
                                    </el-icon>
                                </template>
                                <div class="filter-content">
                                    <el-checkbox-group v-model="filters.gender">
                                        <el-checkbox label="1">男</el-checkbox>
                                        <el-checkbox label="2">女</el-checkbox>
                                    </el-checkbox-group>
                                </div>
                            </el-popover>
                        </div>
                    </template>
                    <template #default="{ row }">
                        {{ row.gender === 1 ? '男' : '女' }}
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机号" width="180">
                    <template #header>
                        <div class="column-header">
                            <span :class="{ 'filtered': filters.phone }">
                                手机号
                                <el-tag v-if="filters.phone" size="small" class="filter-tag">1</el-tag>
                            </span>
                            <el-popover placement="bottom" :width="200" trigger="click">
                                <template #reference>
                                    <el-icon class="filter-icon" :class="{ 'is-filtered': filters.phone }">
                                        <Filter />
                                    </el-icon>
                                </template>
                                <div class="filter-content">
                                    <el-input v-model="filters.phone" placeholder="搜索手机号" clearable />
                                </div>
                            </el-popover>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="idCard" label="身份证" min-width="180">
                    <template #header>
                        <div class="column-header">
                            <span :class="{ 'filtered': filters.idCard }">
                                身份证
                                <el-tag v-if="filters.idCard" size="small" class="filter-tag">1</el-tag>
                            </span>
                            <el-popover placement="bottom" :width="200" trigger="click">
                                <template #reference>
                                    <el-icon class="filter-icon" :class="{ 'is-filtered': filters.idCard }">
                                        <Filter />
                                    </el-icon>
                                </template>
                                <div class="filter-content">
                                    <el-input v-model="filters.idCard" placeholder="搜索身份证" clearable />
                                </div>
                            </el-popover>
                        </div>
                    </template>
                    <template #default="scope">
                        {{ maskIdCard(scope.row.idCard) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                        <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
                <el-form-item label="学号" prop="account">
                    <el-input v-model="form.account" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" type="password" />
                </el-form-item>
                <el-form-item label="学院" prop="college">
                    <el-input v-model="form.college" />
                </el-form-item>
                <el-form-item label="专业" prop="major">
                    <el-input v-model="form.major" />
                </el-form-item>
                <el-form-item label="班级" prop="className">
                    <el-input v-model="form.className" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="form.phone" />
                </el-form-item>
                <el-form-item label="身份证" prop="idCard">
                    <el-input v-model="form.idCard" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>

        <el-dialog title="批量编辑" v-model="batchEditVisible" width="500px">
            <el-form :model="batchForm" label-width="100px">
                <el-form-item label="选择字段">
                    <el-select v-model="batchForm.field">
                        <el-option label="学院" value="college" />
                        <el-option label="专业" value="major" />
                        <el-option label="班级" value="className" />
                    </el-select>
                </el-form-item>
                <el-form-item label="新值">
                    <el-input v-model="batchForm.value" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="batchEditVisible = false">取消</el-button>
                <el-button type="primary" @click="handleBatchEditSubmit">确定</el-button>
            </template>
        </el-dialog>

        <el-dialog title="批量导入学生" v-model="importVisible" width="700px" :close-on-click-modal="false">
            <div class="import-container">
                <div class="drop-zone" @drop.prevent="handleDrop" @dragover.prevent
                    @dragenter.prevent="isDragover = true" @dragleave.prevent="isDragover = false"
                    @click="triggerUpload" :class="{ 'is-dragover': isDragover }" v-if="!previewData.length">
                    <i class="el-icon-upload"></i>
                    <div class="drop-text">点击或将文件拖到此处</div>
                    <div class="drop-hint">
                        支持 .xlsx、.xls 格式
                        <span class="download-link" @click.stop="downloadTemplate">下载模板</span>
                    </div>
                    <input type="file" ref="fileInput" style="display: none" accept=".xlsx,.xls"
                        @change="handleFileSelect" />
                </div>

                <template v-if="previewData.length">
                    <div class="import-stats">
                        <div class="stat-item">
                            <span class="label">总条数：</span>
                            <span class="value">{{ previewData.length }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">成功：</span>
                            <span class="value success">{{ successCount }}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">失败：</span>
                            <span class="value error">{{ errorCount }}</span>
                        </div>
                        <el-button type="primary" size="small" :disabled="!errorCount" @click="downloadErrors">
                            下载错误数据
                        </el-button>
                    </div>

                    <el-table :data="previewData" height="300" border>
                        <el-table-column type="index" label="序号" width="60" fixed="left" />
                        <el-table-column prop="account" label="学号">
                            <template #default="{ row }">
                                <span :class="{ 'error-text': row.error }">{{ row.account }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="姓名">
                            <template #default="{ row }">
                                <span :class="{ 'error-text': row.error }">{{ row.name }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="college" label="学院">
                            <template #default="{ row }">
                                <span :class="{ 'error-text': row.error }">{{ row.college }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="major" label="专业">
                            <template #default="{ row }">
                                <span :class="{ 'error-text': row.error }">{{ row.major }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="className" label="班级">
                            <template #default="{ row }">
                                <span :class="{ 'error-text': row.error }">{{ row.className }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="gender" label="性别">
                            <template #default="{ row }">
                                <span :class="{ 'error-text': row.error }">{{ row.gender === 1 ? '男' : '女' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="phone" label="手机号">
                            <template #default="{ row }">
                                <span :class="{ 'error-text': row.error }">{{ row.phone }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="idCard" label="身份证">
                            <template #default="{ row }">
                                <span :class="{ 'error-text': row.error }">{{ row.idCard }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="error" label="状态" width="150" fixed="right">
                            <template #default="{ row }">
                                <el-tag :type="row.error ? 'danger' : 'success'">
                                    {{ row.error || '正常' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </div>

            <template #footer>
                <el-button @click="importVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmImport"
                    :disabled="!previewData.length || errorCount === previewData.length">
                    确认导入
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import studentApi from '@/store/api/student'
import type { StudentForm, ApiResponse } from "@/types";
import { Search, Filter, Sort } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'

const searchQuery = ref('')
const studentList = ref<StudentForm[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增学生')
const formRef = ref<FormInstance>()
const selectedRows = ref<StudentForm[]>([])
const batchEditVisible = ref(false)
const batchForm = reactive({
    field: '',
    value: ''
})

const form = reactive<StudentForm>({
    id: '',
    account: '',
    name: '',
    password: '',
    college: '',
    major: '',
    className: '',
    gender: 1,
    phone: '',
    idCard: ''
})

const rules = {
    account: [{ required: true, message: '请输入学号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    college: [{ required: true, message: '请输入学院', trigger: 'blur' }],
    major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
    className: [{ required: true, message: '请输入班级', trigger: 'blur' }],
    gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
    // phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    // idCard: [{ required: true, message: '请输入身份证', trigger: 'blur' }]
}

const getStudentList = async () => {
    try {
        const params = searchQuery.value ? { keyword: searchQuery.value } : {};
        const res = await studentApi.getStudentList(params)
        if (res.code === 0) {
            studentList.value = res.data
        } else {
            ElMessage.error(res.message || '获取学生列表失败')
        }
    } catch (error) {
        ElMessage.error('获取学生列表失败')
    }
}

const handleAdd = () => {
    dialogTitle.value = '新增学生'
    dialogVisible.value = true
    form.id = ''
    form.account = ''
    form.name = ''
    form.password = ''
    form.college = ''
    form.major = ''
    form.className = ''
    form.gender = 1
    form.phone = ''
    form.idCard = ''
}

const handleEdit = (row: StudentForm) => {
    dialogTitle.value = '编辑学生'
    dialogVisible.value = true
    form.id = row.id
    form.name = row.name
    form.account = row.account
    form.password = row.password
    form.college = row.college
    form.major = row.major
    form.className = row.className
    form.gender = row.gender
    form.phone = row.phone
    form.idCard = row.idCard
    console.log('row.id', row.id);
}

const handleDelete = (row: StudentForm) => {
    ElMessageBox.confirm('确认删除该学生?', '提示', {
        type: 'warning'
    }).then(async () => {
        try {
            const res = await studentApi.deleteStudent(row.id)
            if (res.code === 0) {
                ElMessage.success('删除成功')
                getStudentList()
            }
        } catch (error) {
            ElMessage.error('删除失败')
        }
    })
}

const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const res = form.id
                    ? await studentApi.updateStudent(form.id, form)
                    : await studentApi.addStudent(form)

                if (res.code === 0) {
                    ElMessage.success(form.id ? '更新成功' : '添加成功')
                    dialogVisible.value = false
                    getStudentList()
                } else {
                    // 显示后端返回具体错误信息
                    ElMessage.error(res.message || '操作失败')
                    console.log('错误响应:', res)
                }
            } catch (error) {
                console.error('请求错误:', error)
                ElMessage.error(form.id ? '更新失败' : '添加失败')
            }
        }
    })
}

const maskIdCard = (idCard: string) => {
    if (!idCard) return '';
    return idCard.slice(0, 4) + '*********' + idCard.slice(-4);
}

const handleSearch = () => {
    getStudentList()
}

const handleClear = () => {
    searchQuery.value = ''
    getStudentList()
}

const handleSelectionChange = (rows: StudentForm[]) => {
    selectedRows.value = rows
}

const handleBatchDelete = () => {
    if (!selectedRows.value.length) return

    ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 名学生?`, '提示', {
        type: 'warning'
    }).then(async () => {
        try {
            const promises = selectedRows.value.map(row => studentApi.deleteStudent(row.id))
            const results = await Promise.all(promises)

            if (results.every(res => res.code === 0)) {
                ElMessage.success('批量删除成功')
                getStudentList()
            } else {
                ElMessage.error('部分删除失败')
            }
        } catch (error) {
            ElMessage.error('批量删除失败')
        }
    })
}

const handleBatchEdit = () => {
    if (!selectedRows.value.length) return
    batchForm.field = ''
    batchForm.value = ''
    batchEditVisible.value = true
}

const handleBatchEditSubmit = async () => {
    if (!batchForm.field || !batchForm.value) {
        ElMessage.warning('请填写完整信息')
        return
    }

    try {
        const promises = selectedRows.value.map(row => {
            const updateData = { ...row, [batchForm.field]: batchForm.value }
            return studentApi.updateStudent(row.id, updateData)
        })

        const results = await Promise.all(promises)

        if (results.every(res => res.code === 0)) {
            ElMessage.success('批量更新成功')
            batchEditVisible.value = false
            getStudentList()
        } else {
            ElMessage.error('部分更新失败')
        }
    } catch (error) {
        ElMessage.error('批量更新失败')
    }
}

const handleExport = async () => {
    try {
        const response = await fetch(`${process.env.VUE_APP_API_URL}student/export`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
        });

        if (!response.ok) throw new Error('导出失败');

        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `学生信息表_${new Date().toLocaleDateString()}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        ElMessage.success('导出成功');
    } catch (error) {
        console.error('导出错误:', error);
        ElMessage.error('导出失败');
    }
};

const handleFileChange = async (file: any) => {
    if (!file) return

    const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase())
    if (!isExcel) {
        ElMessage.error('请上传Excel文件')
        return
    }

    try {
        const formData = new FormData()
        formData.append('file', file.raw)
        const res = await studentApi.importStudents(file.raw)

        if (res.code === 0) {
            ElMessage.success('导入成功')
            getStudentList()
        } else {
            ElMessage.error(res.message || '导入失败')
        }
    } catch (error) {
        ElMessage.error('导入失败')
    }
}

const importVisible = ref(false)
const fileInput = ref<HTMLInputElement | null>(null)
const isDragover = ref(false)
const previewData = ref<any[]>([])
const successCount = computed(() => previewData.value.filter(item => !item.error).length)
const errorCount = computed(() => previewData.value.filter(item => item.error).length)

const showImportDialog = () => {
    importVisible.value = true
    previewData.value = []
}

const downloadTemplate = async () => {
    try {
        const response = await fetch(`${process.env.VUE_APP_API_URL}student/template`, {
            method: 'GET',
        });

        if (!response.ok) throw new Error('下载模板失败');

        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = '学生信息导入模板.xlsx';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        ElMessage.error('下载模板失败');
    }
}

const triggerUpload = () => {
    fileInput.value?.click()
}

const handleFileSelect = (event: Event) => {
    const input = event.target as HTMLInputElement
    if (input.files?.length) {
        handleFile(input.files[0])
    }
}

const handleDrop = (e: DragEvent) => {
    isDragover.value = false
    const files = e.dataTransfer?.files
    if (files?.length) {
        handleFile(files[0])
    }
}

const handleFile = async (file: File) => {
    const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase())
    if (!isExcel) {
        ElMessage.error('请上传Excel文件')
        return
    }

    try {
        // 读取文件内容进行验证
        const reader = new FileReader()
        reader.onload = async (e) => {
            try {
                const data = e.target?.result
                const workbook = XLSX.read(data, { type: 'binary' })
                const worksheet = workbook.Sheets[workbook.SheetNames[0]]
                const headers = XLSX.utils.sheet_to_json(worksheet, { header: 1 })[0] as string[];

                // 验证表头是否符合模板要求
                const requiredHeaders = ['学号', '姓名', '学院', '专业', '班级', '性别', '手机号', '身份证']
                const isValidTemplate = requiredHeaders.every(header => headers.includes(header))

                if (!isValidTemplate) {
                    ElMessage.error('文件格式错误，请使用系统提供的模板')
                    return
                }

                // 验证通过后继续处理
                const formData = new FormData()
                formData.append('file', file)
                const res = await studentApi.previewImport(file)

                if (res.code === 0) {
                    previewData.value = res.data
                    ElMessage.success('文件解析成功')
                } else {
                    ElMessage.error(res.message || '文件解析失败')
                }
            } catch (error) {
                ElMessage.error('文件格式错误，请使用系统提供的模板')
            }
        }

        reader.readAsBinaryString(file)
    } catch (error) {
        ElMessage.error('文件解析失败')
    }
}

const downloadErrors = () => {
    const errorData = previewData.value.filter(item => item.error)
    if (!errorData.length) return

    const mappedData = errorData.map(item => ({
        学号: item.account,
        姓名: item.name,
        学院: item.college,
        专业: item.major,
        班级: item.className,
        性别: item.gender === 1 ? '男' : '女',
        手机号: item.phone || '',
        身份证: item.idCard || '',
        错误信息: item.error
    }))

    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(mappedData)
    XLSX.utils.book_append_sheet(wb, ws, '导入失败数据')
    XLSX.writeFile(wb, `导入失败数据_${new Date().toLocaleDateString()}.xlsx`)
}

const confirmImport = async () => {
    try {
        const validData = previewData.value.filter(item => !item.error)
        if (!validData.length) {
            ElMessage.warning('没有可导入的数据')
            return
        }

        const res = await studentApi.confirmImport(validData)
        if (res.code === 0) {
            ElMessage.success('导入成功')
            importVisible.value = false
            getStudentList()
        } else {
            ElMessage.error(res.message || '导入失败')
        }
    } catch (error) {
        ElMessage.error('导入失败')
    }
}

// 修改筛选状态
const filters = ref({
    account: '',
    className: [] as string[],
    college: [] as string[],
    major: [] as string[],
    gender: [] as string[],
    name: '',
    phone: '',
    idCard: ''
})

// 修改计算属性，让它们基于前面筛选后的结果
const filteredByAccount = computed(() => {
    return studentList.value.filter(student => {
        if (filters.value.account && !student.account.includes(filters.value.account)) {
            return false
        }
        return true
    })
})

const filteredByCollege = computed(() => {
    return filteredByAccount.value.filter(student => {
        if (filters.value.college.length && !filters.value.college.includes(student.college)) {
            return false
        }
        return true
    })
})

const filteredByMajor = computed(() => {
    return filteredByCollege.value.filter(student => {
        if (filters.value.major.length && !filters.value.major.includes(student.major)) {
            return false
        }
        return true
    })
})

const filteredByClass = computed(() => {
    return filteredByMajor.value.filter(student => {
        if (filters.value.className.length && !filters.value.className.includes(student.className)) {
            return false
        }
        return true
    })
})

// 最终筛选结果
const filteredStudentList = computed(() => {
    return filteredByClass.value.filter(student => {
        if (filters.value.gender.length && !filters.value.gender.includes(student.gender.toString())) {
            return false
        }
        return true
    })
})

// 修改选项计算属性，使其基于前面筛选的结果
const collegeOptions = computed(() => {
    const colleges = new Set<string>()
    filteredByAccount.value.forEach(student => {
        if (student.college) {
            colleges.add(student.college)
        }
    })
    return Array.from(colleges)
})

const majorOptions = computed(() => {
    const majors = new Set<string>()
    filteredByCollege.value.forEach(student => {
        if (student.major) {
            majors.add(student.major)
        }
    })
    return Array.from(majors)
})

const classOptions = computed(() => {
    const classes = new Set<string>()
    filteredByMajor.value.forEach(student => {
        if (student.className) {
            classes.add(student.className)
        }
    })
    return Array.from(classes)
})

const sortOrder = ref('ascending') // 'ascending' 或 'descending'
const sortField = ref('account') // 默认按学号排序

const getIndex = (index: number) => {
    return sortOrder.value === 'ascending' ? index + 1 : filteredStudentList.value.length - index
}

const toggleSort = () => {
    sortOrder.value = sortOrder.value === 'ascending' ? 'descending' : 'ascending'
}

const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
    if (prop === 'index') {
        sortOrder.value = order || 'ascending'
    }
}

// 修改筛选和排序逻辑
const sortedAndFilteredList = computed(() => {
    let result = filteredStudentList.value

    result = [...result].sort((a, b) => {
        const field = sortField.value as keyof typeof a
        if (sortOrder.value === 'ascending') {
            return String(a[field]).localeCompare(String(b[field]))
        } else {
            return String(b[field]).localeCompare(String(a[field]))
        }
    })

    return result
})

getStudentList()
</script>

<style scoped>
.student-manage {
    height: calc(100vh - 60px);
    /* 减去顶部导航栏的高度 */
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
}

.fixed-header {
    position: sticky;
    top: 0;
    background-color: #fff;
    z-index: 1;
    padding: 20px 20px 0;
}

.header-actions {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
}

.table-container {
    flex: 1;
    overflow: auto;
    padding: 0 20px 20px;
}

.upload-demo {
    display: inline-block;
    margin-right: 10px;
}

.import-container {
    padding: 20px;
}

.import-header {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
}

.drop-zone {
    border: 2px dashed #dcdfe6;
    border-radius: 6px;
    text-align: center;
    padding: 40px 0;
    margin: 20px 0;
    cursor: pointer;
    transition: all 0.3s;
}

.drop-zone:hover {
    border-color: #409eff;
    background-color: rgba(64, 158, 255, 0.05);
}

.drop-text {
    color: #606266;
    font-size: 14px;
    margin: 10px 0;
}

.drop-hint {
    color: #909399;
    font-size: 12px;
}

.import-stats {
    margin: 20px 0;
    display: flex;
    align-items: center;
    gap: 20px;
}

.stat-item {
    display: flex;
    align-items: center;
}

.stat-item .label {
    color: #606266;
}

.stat-item .value {
    font-weight: bold;
    margin-left: 5px;
}

.stat-item .success {
    color: #67c23a;
}

.stat-item .error {
    color: #f56c6c;
}

.error-text {
    color: #f56c6c;
}

.download-link {
    color: #409eff;
    margin-left: 10px;
    cursor: pointer;
}

.download-link:hover {
    text-decoration: underline;
}

.column-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.filter-icon {
    cursor: pointer;
    font-size: 16px;
    margin-left: 4px;
    color: #909399;
}

.filter-icon:hover {
    color: #409EFF;
}

.filter-content {
    padding: 8px;
}

.filter-content .el-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
    max-height: 200px;
    overflow-y: auto;
}

.el-checkbox {
    margin-right: 0;
    margin-left: 0;
}

.sort-icon {
    font-size: 14px;
    margin-left: 4px;
    color: #909399;
    transition: all 0.3s;
    cursor: pointer;
}

.sort-icon.active {
    color: #409EFF;
}

.sort-icon.desc {
    transform: rotate(180deg);
}

.sort-icon:hover {
    color: #409EFF;
}

.filtered {
    color: #409EFF;
    font-weight: 500;
}

.filter-tag {
    margin-left: 4px;
    height: 16px;
    line-height: 16px;
    padding: 0 4px;
    background-color: #409EFF;
    color: white;
    border-radius: 2px;
    transform: scale(0.8);
    transform-origin: left;
}

.filter-icon.is-filtered {
    color: #409EFF;
}
</style>
